<html>
  <head>
      <meta charset="utf-8">
      <title>Query Result</title>
      <script src="//ajax.googleapis.com/ajax/libs/jquery/1.11.0/jquery.min.js"></script>
      <script src="https://maps.googleapis.com/maps/api/js?sensor=false&v=3.exp&libraries=geometry"></script>
      <script>
var maps = [];
var markers = [];
// All the google maps plotting.
function zoomToObject(map, points){
    var bounds = new google.maps.LatLngBounds();
    for (var n = 0; n < points.length ; n++){
        bounds.extend(points[n]);
    }
    map.fitBounds(bounds);
    setTimeout(function() {
                google.maps.event.trigger(map,'resize');
                map.fitBounds(bounds);
                }, 200);
};

var lineSymbol = {
  path: google.maps.SymbolPath.FORWARD_CLOSED_ARROW
};

function partial(func /*, 0..n args */) {
  var args = Array.prototype.slice.call(arguments, 1);
  return function() {
    var allArguments = args.concat(Array.prototype.slice.call(arguments));
    return func.apply(this, allArguments);
  };
}

function addMarkBox(map, marker, info) {
  var infowindow = new google.maps.InfoWindow({
      content: info
  });
  infowindow.open(map, marker);
}

function plotPoints(divid, neighborhoods, info_beg, info_end) {
  var mapOptions = {}
  maps.push(new google.maps.Map(document.getElementById(divid),
            mapOptions));

  if (neighborhoods.length > 0) {
    markers.push(new google.maps.Marker({
      position: neighborhoods[0],
      map: maps[maps.length-1],
      draggable: false,
      icon: "http://maps.google.com/mapfiles/ms/icons/yellow-dot.png",
      //animation: google.maps.Animation.DROP
    }));
    google.maps.event.addListener(markers[markers.length-1], 'click',
        partial(addMarkBox, maps[maps.length-1], markers[markers.length-1],
                info_beg));
  }
  markers.push(new google.maps.Marker({
    position: neighborhoods[neighborhoods.length - 1],
    map: maps[maps.length-1],
    draggable: false,
    icon: "http://maps.google.com/mapfiles/ms/icons/red-dot.png"
  }));
  google.maps.event.addListener(markers[markers.length-1], 'click',
      partial(addMarkBox, maps[maps.length-1], markers[markers.length-1],
              info_end));

  for (var iter = 1; iter < neighborhoods.length; ++iter) {
    var line = new google.maps.Polyline({
      path: [neighborhoods[iter-1], neighborhoods[iter]],
      icons: [{
        icon: lineSymbol,
        offset: '70%'
      }],
      strokeColor: "#000066",
      strokeOpacity: 0.7,
      strokeWeight: 2,
      geodesic: false,
      map: maps[maps.length-1]
    });
  }
  zoomToObject(maps[maps.length-1], neighborhoods);
};
      </script>
  </head>
  <body onload="LoadMore('{{query.key_inicio}}', '{{query.key_fin}}', 1, 1)">
    <h2>Placa       : {{query.placa}}</h2>
    <h2>Fecha inicio: {{query.inicio_fecha}} {{query.inicio_hora}}</h2>
    <h2>Fecha fin   : {{query.fin_fecha}} {{query.fin_hora}}</h2>
    <br>
    <br>
    <br>
    {{query.key_inicio}} (Begining Key)<br>
    {{query.key_fin}} (End Key)
    <h2>Answers:</h2>
    <div id="answers">
      <table id = "maptable">
         <tr id = "table_row1">
         </tr>
      </table>
      <!--
      <h2 id = "loadmore">
      <center>
        <a href="javascript:LoadMore('{{query.key_inicio}}', '{{query.key_fin}}', 1, 1);">Load More</a>
      </center>
      </h2>
      -->
    </div>
    <script>
        function KeyDate(key) {
          //alert(key);
          var str = key.split("#")[1];
          var i = 0;
          var tmp = "";
          for (var c = 0; c < 4; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var year = tmp;
          tmp = "";
          for (var c = 0; c < 2; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var month = tmp;
          tmp = "";
          for (var c = 0; c < 2; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var day = tmp;
          tmp = "";
          for (var c = 0; c < 2; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var hours = tmp;
          tmp = "";
          for (var c = 0; c < 2; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var minutes = tmp;
          tmp = "";
          for (var c = 0; c < 2; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var seconds = tmp;
          tmp = "";
          for (var c = 0; c < 3; ++c, ++i) {
            tmp = tmp + str.charAt(i);
          }
          var milliseconds= tmp;
          return day + '-' + month + '-' + year + ' ' + hours + ':' + minutes +
                 ':' + seconds + '.' + milliseconds;
        };

        function LoadMore(beg_key, end_key, row_num, col_num){
            $.ajax({
              type: "POST",
              url: "/retrieve/",
              dataType: 'json',
              data: JSON.stringify({'beg_key': beg_key, 'end_key': end_key})
            })
            .done(function(data) {
              var num_records = data['records'].length;
              //alert(''+ num_records + ' records retrieved!!');
              var plottable = [];
              $.each(data['records'], function(index, value) {
                if (index < num_records - 1 && value['key'] <= end_key) {
                  plottable.push(value);
                }
              });
              $('#loadmore').remove();
              var continuar = false;
              if (num_records != 0) {
                var last = data['records'][num_records-1];
                if (last.key != beg_key) {
                  if (last.key < end_key) {
                    continuar = true;
                  } else if(last.key == end_key) {
                    plottable.push(last);
                  }
                } else {
                  plottable.push(last);
                }
              }
              var chunk = 50;
              for (var i = 0; i < plottable.length; i += chunk) {
                var points = [];
                var plot_beg_key = "";
                var plot_end_key = "";
                for (var j = i; j < i + chunk && j < plottable.length; ++j) {
                  var point = new google.maps.LatLng(
                      parseFloat(plottable[j].lat),
                      parseFloat(plottable[j].lon));
                  if (j != i) {
                    if (j == i + chunk - 1) {
                      plot_end_key = plottable[j].key;
                      points.push(point);
                    } else if (google.maps.geometry.spherical
                                  .computeDistanceBetween(
                                        points[points.length-1], point) > 40) {
                      points.push(point);
                    }
                  } else {
                    plot_beg_key = plottable[j].key;
                    plot_end_key = plottable[j].key;
                    points.push(point);
                  }
                }
                $('#table_row' + row_num).append('<td><div' + ' id=\"' +
                    plottable[i].key + '\" ' +
                    'style=\"width:400px; height:400px;\">'+
                    '</div></td>');
                var info_beg =
                    '<p><b>Fecha: ' + KeyDate(plot_beg_key) +'</b></p>' +
                    '<p><b>Coord: ' + points[0].toString() + '</b></p>';

                var info_end=
                  '<p><b>Fecha: ' + KeyDate(plot_end_key) + '</b></p>' +
                  '<p><b>Coord: ' + points[points.length-1].toString() +
                  '</b></p>';
                plotPoints(plottable[i].key, points, info_beg, info_end);

                col_num = col_num + 1;
                if (col_num > 3) {
                  col_num = 1;
                  row_num = row_num + 1;
                  $('#maptable').append(
                      '<tr id=\"table_row' + row_num + '\"> </tr>');
                }
              }
              if (continuar) {
                var last = data['records'][num_records - 1];
                $('#answers').append(
                    '<h2 id=\"loadmore\"><center>' +
                    '<a href=\"javascript:LoadMore(\'' +
                    last.key + '\', \'' + end_key +'\',' + row_num + ', '  +
                    col_num + ');\">Load More</a>' +
                    '</center></h2>'
                );
              } else {
                $('#answers').append(
                    '<center>' +
                    '<h2> No more elements to get! </h2>' +
                    '</center');
              }
            });
        };
    </script>
  </body>
</html>

